package com.hongji.lms5xxcommunicator.opc.sub;

import com.hongji.lms5xxcommunicator.opc.util.OpcNodeResolver;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem;
import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription;
import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem.ValueConsumer;
import org.eclipse.milo.opcua.stack.core.AttributeId;
import org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName;
import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned;
import org.eclipse.milo.opcua.stack.core.types.enumerated.MonitoringMode;
import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn;
import org.eclipse.milo.opcua.stack.core.types.structured.*;

import java.util.Collections;
import java.util.List;

@Slf4j
public class MonitoredItemHelper {

    public static List<UaMonitoredItem> addWithCallback(
            UaSubscription subscription,
            String nodeId,
            double samplingInterval,
            ValueConsumer valueConsumer,
            OpcNodeResolver resolver,
            OpcUaClient client
    ) throws Exception {
        ReadValueId valueId = new ReadValueId(
                resolver.resolveFlexible(client, nodeId),
                AttributeId.Value.uid(),
                null,
                QualifiedName.NULL_VALUE
        );
        MonitoringParameters param = new MonitoringParameters(
                subscription.nextClientHandle(),
                samplingInterval,
                null,
                Unsigned.uint(10),
                true
        );
        MonitoredItemCreateRequest req = new MonitoredItemCreateRequest(
                valueId, MonitoringMode.Reporting, param);

        List<UaMonitoredItem> created = subscription.createMonitoredItems(
                TimestampsToReturn.Both,
                Collections.singletonList(req),
                (item, id) -> item.setValueConsumer(valueConsumer)
        ).get();

        return created;
    }
}
